package com.itCar.base.api.entityJson.service.impl;

import com.itCar.base.api.entityJson.entity.EntityVo;
import com.itCar.base.api.entityJson.service.EntityJsonService;
import com.itCar.base.tools.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName EntityJsonServiceImpl
 * @Description TODO 补充说明:
 * @Author liuzhiguo
 * @Date 2024/1/2 16:07
 * @Version 1.0
 */
@Service
public class EntityJsonServiceImpl implements EntityJsonService {
    private static final String URL_PREFIX = "jdbc:mysql://";
    private static final String URL_SUFFIX = "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true";

    @Override
    public JSONArray getEntityJson(EntityVo entityVo) {
        String url = URL_PREFIX + entityVo.getUrl() + URL_SUFFIX;
        String userName = entityVo.getUserName();
        String password = entityVo.getPassword();
        String name = entityVo.getTableName();
        JSONArray tableList = null;
        try (
                Connection conn = DriverManager.getConnection(url, userName, password)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet tablesResultSet = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            // 表结构返回
            tableList = new JSONArray();
            Map<String, Object> map = null;
            boolean flag = false;
            // 循环数据库中所有的表
            while (tablesResultSet.next()) {
                if (flag) {
                    break;
                }
                // 拿到每一次的表名称
                String tableName = tablesResultSet.getString("TABLE_NAME");
                ResultSet columnsResultSet = null;
                // 若指定某张表 只返回指定 否则返回全部
                if (StringUtils.isNotEmpty(name)) {
                    if (name.equals(tableName)) {
                        columnsResultSet = metaData.getColumns(null, null, name, "%");
                        flag = true;
                    } else {
                        continue;
                    }
                } else {
                    columnsResultSet = metaData.getColumns(null, null, tableName, "%");
                }
                // 存储表结构信息
                JSONObject tableInfo = new JSONObject();
                // 存储表名称
                tableInfo.put("tableName", tableName);
                // 存储表列结构信息 例如：{"id":"主键"}
                StringBuilder sb = new StringBuilder("{");
                map = new HashMap<>();
                while (columnsResultSet.next()) {
                    // 列名
                    String columnName = StringUtils.convertToCamelCase_new(columnsResultSet.getString("COLUMN_NAME"));
                    // 列名注释
                    String columnRemark = columnsResultSet.getString("REMARKS");
                    // 拼接JSON格式 例如：{"id":"主键"}
                    sb.append("\"").append(columnName).append("\"").append(":");
                    sb.append("\"").append(columnRemark).append("\"");
                    if (!columnsResultSet.isLast()) {
                        sb.append(",");
                    }
                    map.put('"'+columnName+'"','"'+columnRemark+'"');
                }
                sb.append("}");
                tableInfo.put("tableFormat", sb);
                tableList.add(tableInfo);
            }

            System.out.println(tableList.toJSONString());
            System.out.println(map);
            System.out.println("共" + tableList.size() + "张表");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tableList;
    }
}
